/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ReadXML;

import ImageCache.ImageCache;
import Welcome.DownloadAlert;
import Welcome.DrawChoice;
import Welcome.KeyCodeAdapter;
import Welcome.KhoiDong;
import Welcome.LevelActivated;
import Welcome.Start;
import Welcome.TangToc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

public class LoadImageFromServer extends Canvas {

    private RecordStore records_name, images_name, imagesList, image_Names;
    private int LEVEL, imgId = 1, instanceKeyCode;
    private Start midlet;
    private DownloadAlert da;
    private final String RECORD_NAME = "ImageInfo";
    private final String IMAGES_NAME = "ImageName";
    private static final String IMAGES_RS = "ImageList";
    private boolean wait = false, trucking = true;
    private Image bufferImage;
    private int hfColor = 0xEA9414;
    private int percent = 0;
    private Thread t;
    private Font f;
    ImageCache imageCache;

    public LoadImageFromServer(Start midlet) {
        this.setFullScreenMode(true);
        bufferImage = Image.createImage(getWidth(), getHeight());
        f = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
        this.midlet = midlet;
        imageCache = ImageCache.getInstance();

        deleteRecordStore();
        try {
            images_name = RecordStore.openRecordStore(IMAGES_NAME, true);
            image_Names = RecordStore.openRecordStore("Image_Names", false);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
    }

    private void deleteRecordStore() {
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore rc1 = null;
                try {
                    rc1 = RecordStore.openRecordStore(IMAGES_RS, false);
                } catch (RecordStoreNotFoundException e) {
                    e.printStackTrace();
                }

                if (rc1 != null) {
                    rc1.closeRecordStore();
                    RecordStore.deleteRecordStore(IMAGES_RS);
                    System.out.println("delete3");
                }
            } catch (RecordStoreException ex) {
                ex.printStackTrace();
                System.out.println(ex.toString());
            }
        }
    }

    private String[] getUrl() {
        String[] url = null;
        Random random = new Random();
        try {
            if (DrawChoice.khoiDong) {
                url = new String[10];
                int i = (random.nextInt() << 5) % 3;
                if (i < 0) {
                    i = -i;
                }
                for (int j = 0; j < 10; j++) {
                    byte[] urlByte = images_name.getRecord(i + j + 1);
                    DrawChoice.KD[j] = i + j + 1;
                    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(urlByte));
                    try {
                        url[j] = dis.readUTF();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
/////////////////////////////////////////////////////////////////
                    /*
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream data = new DataOutputStream(baos);
                    try {
                    data.writeInt(DrawChoice.KD[j]);
                    data.flush();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }


                    byte[] rec = baos.toByteArray();
                    try {
                    image_Names.addRecord(rec, 0, rec.length);
                    } catch (RecordStoreNotOpenException ex1) {
                    ex1.printStackTrace();
                    } catch (InvalidRecordIDException ex1) {
                    ex1.printStackTrace();
                    } catch (RecordStoreException ex1) {
                    ex1.printStackTrace();
                    }

                    try {
                    data.close();
                    baos.close();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }
                     */
///////////////////////////////////////////////////////////////////
                }
            } else if (DrawChoice.tangToc) {
                url = new String[7];
                int i = (random.nextInt() << 5) % 8 + 12;
                if (i < 0) {
                    i = -i;
                }
                for (int j = 0; j < 7; j++) {
                    byte[] urlByte = images_name.getRecord(i + j + 1);
                    System.out.println(i + j + 1);
                    DrawChoice.TT[j] = i + j + 1;
                    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(urlByte));
                    try {
                        url[j] = dis.readUTF();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
/////////////////////////////////////////////////////////////////
                    /*
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream data = new DataOutputStream(baos);
                    try {
                    data.writeInt(DrawChoice.TT[j]);
                    data.flush();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }


                    byte[] rec = baos.toByteArray();
                    try {
                    image_Names.addRecord(rec, 0, rec.length);
                    } catch (RecordStoreNotOpenException ex1) {
                    ex1.printStackTrace();
                    } catch (InvalidRecordIDException ex1) {
                    ex1.printStackTrace();
                    } catch (RecordStoreException ex1) {
                    ex1.printStackTrace();
                    }

                    try {
                    data.close();
                    baos.close();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }
                     *
                     */
///////////////////////////////////////////////////////////////////
                }
            } else if (DrawChoice.veDich) {
                url = new String[10];
                int i = (random.nextInt() << 5) % 3;
                if (i < 0) {
                    i = -i;
                }
                i = 21 - i;
                for (int j = 0; j < 10; j++) {
                    byte[] urlByte = images_name.getRecord(i + j);
                    DrawChoice.VD[j] = i + j;
                    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(urlByte));
                    try {
                        url[j] = dis.readUTF();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }

/////////////////////////////////////////////////////////////////
                    /*
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    DataOutputStream data = new DataOutputStream(baos);
                    try {
                    data.writeInt(DrawChoice.VD[j]);
                    data.flush();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }


                    byte[] rec = baos.toByteArray();
                    try {
                    image_Names.addRecord(rec, 0, rec.length);
                    } catch (RecordStoreNotOpenException ex1) {
                    ex1.printStackTrace();
                    } catch (InvalidRecordIDException ex1) {
                    ex1.printStackTrace();
                    } catch (RecordStoreException ex1) {
                    ex1.printStackTrace();
                    }

                    try {
                    data.close();
                    baos.close();
                    } catch (IOException ex1) {
                    ex1.printStackTrace();
                    }
                     *
                     */
///////////////////////////////////////////////////////////////////
                }
            }
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (InvalidRecordIDException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        try {
            images_name.closeRecordStore();
        } catch (RecordStoreNotOpenException ex) {
            ex.printStackTrace();
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }
        return url;
    }

    public void parse() {
        t = new Thread() {

            String[] url = getUrl();

            public void run() {
                int n = url.length;
                int i = 0;
                boolean running = true;
                while (running) {
                    imageCache.getImageOverHttp(url[i]);
                    percent = 100 * (i + 1) / n;
                    repaint();
                    i++;
                    if (i == n) {
                        running = false;
                    }
                }
                closeRecord();
                nextDisplay();
            }
        };
        t.start();
    }

    private void createRecord(int level) {
        RecordStore levelActived = null;
        try {
            levelActived = RecordStore.openRecordStore("LevelActived", false);
        } catch (RecordStoreException ex) {
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream data = new DataOutputStream(baos);
        try {
            data.writeInt(level);
            data.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        byte[] rec = baos.toByteArray();

        try {
            levelActived.setRecord(2, rec, 0, rec.length);
        } catch (RecordStoreException ex) {
            ex.printStackTrace();
        }

        try {
            data.close();
            baos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        rec = null;
        System.gc();
    }

    private void nextDisplay() {
        if (DrawChoice.khoiDong) {
//            createRecord(1);
            DrawChoice.demBai = 0;
            DrawChoice.tangToc = DrawChoice.tt = false;
            DrawChoice.veDich = DrawChoice.vd = false;
            midlet.disManager.pushDisplayable(new KhoiDong(midlet, 60));
        } else if (DrawChoice.tangToc) {
//            createRecord(2);
            DrawChoice.khoiDong = DrawChoice.kd = false;
            DrawChoice.veDich = DrawChoice.vd = false;
            midlet.disManager.pushDisplayable(new TangToc(midlet, 50));
        } else if (DrawChoice.veDich) {
//            createRecord(3);
            DrawChoice.khoiDong = DrawChoice.kd = false;
            DrawChoice.tangToc = DrawChoice.tt = false;
            midlet.disManager.pushDisplayable(new LevelActivated(midlet, 40));
        }
    }

    public void closeRecord() {

        if (records_name != null) {
            try {
                records_name.closeRecordStore();
                System.out.println("close1");
            } catch (Exception e) {
                System.out.println("Exception " + e.toString());
            }
        }
        if (images_name != null) {
            try {
                images_name.closeRecordStore();
                System.out.println("close1");
            } catch (Exception e) {
                System.out.println("Exception " + e.toString());
            }
        }
    }

    protected void paint(Graphics g) {
        renderTheWorld();
        g.drawImage(bufferImage, 0, 0, Graphics.LEFT | Graphics.TOP);
    }

    public void renderTheWorld() {
        Graphics g = bufferImage.getGraphics();
        g.setColor(0xFCF93A);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setFont(f);
        g.setColor(0x000000);
        g.drawString("Downloading...", getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.BASELINE);
        g.drawString(String.valueOf(percent) + "%", getWidth() / 2, getHeight() / 2 + f.getHeight() + 2,
                Graphics.HCENTER | Graphics.BASELINE);

        g.setColor(hfColor);
        g.fillRect(0, getHeight() - f.getHeight() - 4, getWidth(), f.getHeight() + 4);
        g.setColor(0xffffff);
        g.drawLine(0, getHeight() - f.getHeight() - 4, getWidth(), getHeight() - f.getHeight() - 4);
        g.drawString("Thoát", 1, getHeight() - 2, Graphics.LEFT | Graphics.BOTTOM);
    }

    protected void pointerPressed(int x, int y) {
        if (x <= getWidth() && x >= 0) {
            if (y <= getHeight() && y >= 0) {
                DrawChoice.LEVEL--;
                closeRecord();
                wait = true;
                trucking = false;
                midlet.disManager.popDisplayable();
            }
        }
    }

    protected void keyPressed(int keyCode) {
        instanceKeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keyCode);

        switch (instanceKeyCode) {
            case KeyCodeAdapter.SOFT_KEY_LEFT:
                DrawChoice.LEVEL--;
                closeRecord();
                wait = true;
                trucking = false;
                midlet.disManager.popDisplayable();
        }
    }
}
